
YAHOO.namespace('springmole.QueryPanel');

(function () {

YAHOO.springmole.QueryPanel = function(el, userConfig) {
  YAHOO.springmole.QueryPanel.superclass.constructor.call(this, el, userConfig);
};



var DEFAULT_CONFIG = {

	TABLE_ELEMENT : 'tableElement',
	CONNECTION_DATA : 'connectionData'
		
};

var DATASOURCE_URL = 'database.spy';


var getYUIColumnFromSQLType = function(sqlType) {
	switch(sqlType) {
		case	2003:	// ARRAY
		case	2001:	// DISTINCT
		case	70:		// DATALINK
		case	2000:	// JAVA_OBJECT
		case	0:		// NULL
		case	1111:	// OTHER
		case	2006:	// REF
		case	2002:	// STRUCT
			return {
				formatter	: 'textarea',
				parser		: 'string'
			};
			break;
			
		case	16:		// BOOLEAN
		case	-7:		// BIT
			return {
				formatter	: 'text',
				parser		: 'string'
			};
			break;
			
		case	-2:		// BINARY 	
		case	2004:	// BLOB 	
		case	2005:	// CLOB 	
			return '';
			break;
			
		case	92:		// TIME
		case	93:		// TIMESTAMP
		case	91:		// DATE
			return {
				formatter	: function(elCell, oRecord, oColumn, oData) {
					try {
						var oDate = oData;
       			elCell.innerHTML = oDate.toString('yyyy-MM-dd HH:mm:ss');
					} catch(e) {
						elCell.innerHTML = 'Parse error';
					}
				},
				parser		: function(data) {
       		try {
						return Date.parseExact(data, 'yyyy-MM-ddTHH:mm:ss');
					} catch(e) {
						return false;
					}
				}
			};
			break;
			
		case	3:		// DECIMAL
		case	-5:		// BIGINT				
		case	8:		// DOUBLE
		case	6:		// FLOAT
		case	4:		// INTEGER
		case	-6:		// TINYINT
		case	7:		// REAL
		case	2:		// NUMERIC
		case	5: 		// SMALLINT
			return {
				formatter	: 'number',
				parser		: 'number'
			};
			break;

		case	1:		// CHAR																					
		case	12:		// VARCHAR
			return {
				formatter	: 'text',
				parser		: 'string'
			};
			break;		
		
		case	-4:		// LONGVARBINARY
		case	-1:		// LONGVARCHAR
		case	-3:		// VARBINARY
			return {
				formatter	: 'textarea',
				parser		: 'string'
			};
			break;
	}
}


var initTable = function(tableId, width, height, tableElement, connectionData) {
	var columnConfigArray = new Array();
	var dataSourceFieldArray = new Array();
	
	for (var columnIndex = 0; columnIndex < tableElement.childNodes.length; columnIndex++) {
  	var column = tableElement.childNodes[columnIndex];
		var yuiColumn = getYUIColumnFromSQLType(parseInt(column.getAttribute('sqlType')));
		var clolumnName = column.getAttribute('name');
		
		columnConfigArray.push({
			key				: clolumnName,
			label			: clolumnName,
			formatter	:	yuiColumn.formatter,
			sortable	: true
		});
		
		dataSourceFieldArray.push({
			key				: clolumnName,
			parser		: yuiColumn.parser,
			locator		: '@' + clolumnName
		});
  }
	
  var dataSource = new YAHOO.util.DataSource(DATASOURCE_URL);
	dataSource.connMethodPost = true;
  dataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
	dataSource.useXPath = true;
  dataSource.responseSchema = {
      resultNode: 'Row',
      fields: dataSourceFieldArray
  };

	var requestBuilder = function(oState, oSelf) {
		// Get states or use defaults
		oState = oState || { pagination: null, sortedBy: null };
		var sort = (oState.sortedBy) ? oState.sortedBy.key : 'id';
		var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? 'desc' : 'asc';
		var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
		var results = (oState.pagination) ? oState.pagination.rowsPerPage : 100;

		// Build custom request
		return "sort=" + sort +
		        '&dir=' + dir +
		        "&startIndex=" + startIndex +
		        "&results=" + (startIndex + results - 1) +
						'&query=SELECT * FROM ' + tableElement.getAttribute('name') + 
						'&url=jdbc:postgresql://localhost/migrate' +
						'&userName=postgres' +
						'&password=postgres';
	};

	var dataTable = new YAHOO.widget.ScrollingDataTable(tableId, columnConfigArray, dataSource, {
		dynamicData: true, 
		width: width + 'px',
		height: height + 'px',
		draggableColumns: true,
		generateRequest: requestBuilder,
		initialRequest: 'query=SELECT * FROM ' + tableElement.getAttribute('name') + '&url=jdbc:postgresql://localhost/migrate&userName=postgres&password=postgres&sort=id&dir=asc&startIndex=0&results=10'
	});
	
	return dataTable;
}

YAHOO.lang.extend(YAHOO.springmole.QueryPanel, YAHOO.springmole.SpringMolePanel, {
	  
	initDefaultConfig: function () {
		YAHOO.springmole.QueryPanel.superclass.initDefaultConfig.call(this);
		this.cfg.addProperty(DEFAULT_CONFIG.TABLE_ELEMENT, {});
		this.cfg.addProperty(DEFAULT_CONFIG.CONNECTION_DATA, {});
	},
	
  render: function(parentNode) {
		var _this = this;
		var bodyId = this.id + '_body';
		var tableId = this.id + '_dynamicdata';
		var dataTable;
		
		this.setHeader('Test Panel');
		this.setBody('<div id="' + bodyId + '"></div>');
		
		YAHOO.springmole.QueryPanel.superclass.render.call(this, parentNode);
		
		var tableElement = _this.cfg.getProperty(DEFAULT_CONFIG.TABLE_ELEMENT);
			
		var layout = new YAHOO.widget.Layout(bodyId, {
	    height: (this.body.offsetHeight - 20),
	    width: 480,
	    units: [{
        position: 'top',
        height: 25,
        resize: true,
        header: 'SELECT * FROM ' + tableElement.getAttribute('name'),
        gutter: '0 0 6 0',
        scroll: false
	    }, {
        position: 'center',
        body: '<div id="' + tableId + '"></div>',
        gutter: '0 0 0 0',
        scroll: false
	    }, {
        position: 'bottom',
        height: 25,
        body: 'Bottom',
        gutter: '6 0 0 0'
	    }]
		});
			
		layout.on('render', function() {
			var region = YAHOO.util.Dom.getRegion(_this.body);
			var elmHeight = region.bottom - region.top;
			var elmWidth = region.right - region.left;
			
			dataTable = initTable(tableId, elmWidth, elmHeight, tableElement, _this.cfg.getProperty(DEFAULT_CONFIG.CONNECTION_DATA));
			//dataTable.set('height', elmHeight + 'px');
			//dataTable.set('width', elmWidth + 'px');
		});
					
		layout.render();

    var unitTop = layout.getUnitByPosition('top');
    unitTop.on('click', function(e){
      if(!this.get('body')) {
        var headerText = this.get('header');

        this.set('header', 'Query');
        this.set('body', '<textarea class="sqlTextEditor" id="sqlTextEditor"></textarea>');
        this.set('footer', '<input type="button" id="pushbutton1" name="button1" value="Add"><input type="button" id="pushbutton2" name="button2" value="Add"><input type="button" id="pushbutton3" name="button3" value="Add"><input type="button" id="pushbutton4" name="button4" value="Add"><input type="button" id="pushbutton5" name="button5" value="Add">');
        this.set('height', 150);

        Dom.get('sqlTextEditor').innerHTML = headerText;
      }
    });
		
		this._panelResize.on('resize', function(args) {
	 		var panelHeight = args.height;
			YAHOO.util.Dom.setStyle(this.body, 'height', (panelHeight - 45) + 'px');	 	

			dataTable.set('height', (panelHeight - 122) + 'px');
			dataTable.set('width', (args.width - 23) + 'px'); 
			 
			layout.set('height', (panelHeight - 45));
			layout.set('width', (args.width - 20));
			layout.resize();
		}, this, true);

	} // render
	  
}); // extend Panel


}());